﻿namespace SLClient.InterativeBehaviors
{
    using System;
    using System.Windows.Automation.Peers;
    using System.Windows.Automation.Provider;
    using System.Windows.Controls.Primitives;
    using System.Windows.Input;
    using System.Windows.Interactivity;

    public class TextBoxEnterBehaviour : TargetedTriggerAction<ButtonBase>
    {
        private AutomationPeer peer;
        private ButtonBase targetedButton;

        protected override void Invoke(object parameter)
        {
            KeyEventArgs args = parameter as KeyEventArgs;
            if (((args != null) && (args.Key == Key.Enter)) && ((this.peer != null) && this.peer.IsEnabled()))
            {
                (this.peer.GetPattern(0) as IInvokeProvider).Invoke();
            }
        }

        protected override void OnAttached()
        {
            base.OnAttached();
            this.targetedButton = base.Target;
            if (null != this.targetedButton)
            {
                this.peer = FrameworkElementAutomationPeer.FromElement(this.targetedButton);
                if (this.peer == null)
                {
                    this.peer = FrameworkElementAutomationPeer.CreatePeerForElement(this.targetedButton);
                }
            }
        }

        protected override void OnTargetChanged(ButtonBase oldTarget, ButtonBase newTarget)
        {
            base.OnTargetChanged(oldTarget, newTarget);
            this.targetedButton = newTarget;
            if (null != this.targetedButton)
            {
                this.peer = FrameworkElementAutomationPeer.FromElement(this.targetedButton);
                if (this.peer == null)
                {
                    this.peer = FrameworkElementAutomationPeer.CreatePeerForElement(this.targetedButton);
                }
            }
        }
    }
}

